package com.weetop.cfw.other

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.github.lzyzsd.jsbridge.BridgeWebViewClient
import com.weetop.cfw.R
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.utils.WebViewSettingUtils
import kotlinx.android.synthetic.main.activity_common_web_view.*
import kotlinx.android.synthetic.main.activity_rich_text_web_view.*

/**
 * H5界面
 */
class CommonWebViewActivity : CommonBaseActivity(), View.OnClickListener {

    private var commonUrl: String? = null
    private var isUrl: Boolean = true

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.imageCommonBack -> ActivityUtils.finishActivity(this)
        }
    }

    companion object {

        const val COMMON_URL_KEY = "common_url_key"
        const val COMMON_CONTENT_KEY = "common_content_key"
        const val PHONE = "phone"

        fun startCommonWebViewActivity(context: Context, url: String) {
            val intent = Intent(context, CommonWebViewActivity::class.java)
            intent.putExtra(COMMON_URL_KEY, url)
            ActivityUtils.startActivity(intent)
        }

        fun startCommonWebViewContentActivity(context: Context, content: String) {
            val intent = Intent(context, CommonWebViewActivity::class.java)
            intent.putExtra(COMMON_CONTENT_KEY, content)
            intent.putExtra("isUrl", false)

            ActivityUtils.startActivity(intent)
        }

        fun startCommonWebViewContentActivity(context: Context, content: String, phone: String) {
            val intent = Intent(context, CommonWebViewActivity::class.java)
            intent.putExtra(COMMON_CONTENT_KEY, content)
            intent.putExtra(PHONE, phone)
            intent.putExtra("isUrl", false)

            ActivityUtils.startActivity(intent)
        }
    }

    override fun getLayoutId() = R.layout.activity_common_web_view

    override fun initView(savedInstanceState: Bundle?) {
        setViewsOnClickListener(this, imageCommonBack)
    }

    override fun initData(savedInstanceState: Bundle?) {
        commonUrl = intent.getStringExtra(COMMON_URL_KEY)
        if (StringUtils.isEmpty(commonUrl))
            commonUrl = intent.getStringExtra(COMMON_CONTENT_KEY)
        isUrl = intent.getBooleanExtra("isUrl", true)
        LogUtils.d("COMMON_URL_KEY", commonUrl)
        textCommonTitle.text = "详情"
        var phone1 = intent.getStringExtra(PHONE)
        if (!TextUtils.isEmpty(phone1)) {
            phone.visibility = View.VISIBLE
            phone.text = "联系电话：" + intent.getStringExtra(PHONE)
            phone.setOnClickListener {
                val intent = Intent(Intent.ACTION_DIAL)
                val data = Uri.parse("tel:" + phone1)
                intent.data = data
                startActivity(intent)
            }
        } else {
            phone.visibility = View.GONE
        }
        initWebView()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && commonWebView.canGoBack()) {
            commonWebView.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 初始化WebView
     */
    private fun initWebView() {
        commonWebView.webViewClient = object : BridgeWebViewClient(commonWebView) {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                return false// 返回false
            }
        }

        commonWebView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
//                textCommonTitle.text = title
            }
        }
        val webSettings = commonWebView.settings
        // 让WebView能够执行javaScript
        webSettings.javaScriptEnabled = true
        // 让JavaScript可以自动打开windows
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        // 设置缓存
        webSettings.setAppCacheEnabled(true)
        // 设置缓存路径
//        webSettings.setAppCachePath("")
        // 支持缩放(适配到当前屏幕)
        /* webSettings.setSupportZoom(true)
         // 将图片调整到合适的大小
         webSettings.useWideViewPort = true
         // 支持内容重新布局,一共有四种方式
         // 默认的是NARROW_COLUMNS
         webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
         // 设置可以被显示的屏幕控制
         webSettings.displayZoomControls = true

         // 设置WebView支持JavaScript
         webSettings.setJavaScriptEnabled(true);
         //支持自动适配
         webSettings.setUseWideViewPort(true);
         webSettings.setLoadWithOverviewMode(true);
         webSettings.setSupportZoom(true);  //支持放大缩小
         webSettings.setAllowFileAccess(true); // 允许访问文件
         webSettings.setSaveFormData(true);
         webSettings.setGeolocationEnabled(true);
         webSettings.setDomStorageEnabled(true);
         webSettings.setJavaScriptCanOpenWindowsAutomatically(true);/// 支持通过JS打开新窗口
         webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
         webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);*/
        if (isUrl) {
            commonWebView.loadUrl(commonUrl)
        } else {
            val settings = commonWebView.settings
            settings.javaScriptEnabled = true //支持JS

            val js = "<script type=\"text/javascript\">" +
                    "var imgs = document.getElementsByTagName('img');" +  // 找到img标签
                    "for(var i = 0; i<imgs.length; i++){" +  // 逐个改变
                    "imgs[i].style.width = '100%';" +  // 宽度改为100%
                    "imgs[i].style.height = 'auto';" +
                    "}" +
                    "</script>"
            commonWebView.loadData(
                Html.fromHtml(commonUrl).toString() + js,
                "text/html; charset=UTF-8",
                null
            )
//            commonWebView.loadData(Html.fromHtml(commonUrl).toString(), "text/html; charset=UTF-8", null)
        }
        WebViewSettingUtils.initWebView(commonWebView)
    }

}
